package com.lp.common.component;

import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.lp.common.exception.BaseException;
import com.lp.common.exception.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;

/**
 * @program: biz
 * @description:
 * @author: Ke.Song
 * @since: 2024-03-23 22:32:18
 */
@Slf4j
@Service
public class AliService {

    @Value("${ali.oss.bucketName}")
    private String bucketName;

    @Value("${ali.oss.bucketHost}")
    private String bucketHost;

    @Autowired
    private DefaultAcsClient acsClient;

    @Value("${ali.sts.arn}")
    private String arn;

    @Value("${ali.sts.sessionName}")
    private String sessionName;

    @Value("${ali.sts.durationSeconds}")
    private Long durationSeconds;

    @Autowired
    private OSS oss;

    public String putObject(String fileName, MultipartFile file, String... path) {
        fileName = fileName == null ? Objects.requireNonNull(file.getOriginalFilename()) : fileName;
        return putObject(fileName, file.getResource(), path);
    }

    public String putObject(String fileName, Resource file, String... path) {
        String finalPath = "";
        for (String s : path) {
            finalPath = finalPath.concat(s).concat("/");
        }
        finalPath = finalPath.concat(fileName);
        try (InputStream inputStream = file.getInputStream()) {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, finalPath, inputStream);
            putObjectRequest.setProcess("true");
            PutObjectResult putObjectResult = oss.putObject(putObjectRequest);
            System.out.println(JSONUtil.toJsonStr(putObjectResult));
            return bucketHost + finalPath;
        } catch (Exception e) {
            System.out.printf("文件上传失败：%s%n", e.getMessage());
        }
        return null;
    }

    public AssumeRoleResponse.Credentials getAcsResponse() {
        log.info("OSS: 获取STS Token");
        try {
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(arn);
            request.setRoleSessionName(sessionName);
            request.setDurationSeconds(durationSeconds);
            AssumeRoleResponse acsResponse = acsClient.getAcsResponse(request);
            return acsResponse.getCredentials();
        } catch (ClientException e) {
            log.info("OSS: 获取STS Token错误，错误信息：{}", e.getErrMsg());
            throw new BaseException(ErrorCodeEnum.PARAMS_ERROR);
        }
    }
}
